package com.vn.toaa.karaoke.ui;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;

import com.vn.toaa.karaokecodelist.R;

public class ClearableEditText extends RelativeLayout {
	LayoutInflater inflater = null;
	EditText edit_text;
	Button btn_clear;
	private IAfterTextChangedListener mAfterTextChanged;
	
	public interface IAfterTextChangedListener {
		void onAfterTextChanged();
	}

	public ClearableEditText(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		initViews();
	}

	public ClearableEditText(Context context, AttributeSet attrs) {
		super(context, attrs);

		initViews();

	}

	public ClearableEditText(Context context) {
		super(context);

		initViews();
	}

	void initViews() {
		inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		inflater.inflate(R.layout.clearable_edit_text, this, true);
		edit_text = (EditText) findViewById(R.id.clearable_edit);
		edit_text.setTextSize(TypedValue.COMPLEX_UNIT_SP , 16);
		btn_clear = (Button) findViewById(R.id.clearable_button_clear);
		btn_clear.setVisibility(RelativeLayout.INVISIBLE);
		clearText();
		showHideClearButton();
	}

	void clearText() {
		btn_clear.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				edit_text.setText("");
			}
		});
	}
	
	public void setText(String newText) {
		edit_text.setText(newText);
	}
	
	public void setHintText(String inputText) {
		edit_text.setHint(inputText);
	}

	void showHideClearButton() {
		edit_text.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				
				if (s.length() > 0)
					btn_clear.setVisibility(RelativeLayout.VISIBLE);
				else
					btn_clear.setVisibility(RelativeLayout.INVISIBLE);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				

			}

			@Override
			public void afterTextChanged(Editable s) {
				if (mAfterTextChanged != null) {
					mAfterTextChanged.onAfterTextChanged();
				}
			}
		});
	}

	public Editable getText() {
		Editable text = edit_text.getText();
		return text;
	}
	
	public void setIAfterTextChangedListener(IAfterTextChangedListener afterTextChanged) {
		this.mAfterTextChanged = afterTextChanged;
	}
}
